package com.hxc.shop.service;

import com.hxc.shop.bean.ShopUserInfo;
import com.hxc.shop.bean.Vo.UserRegistrationVo;
import com.hxc.shop.common.ResultCode;
import com.hxc.shop.common.ResultVO;
import com.hxc.shop.mapper.Mysql.AddressMapper;
import com.hxc.shop.mapper.Mysql.UserMapper;
import lombok.extern.slf4j.Slf4j;
import org.springframework.stereotype.Service;
import org.springframework.util.StringUtils;

import javax.annotation.Resource;
import java.text.SimpleDateFormat;
import java.util.Date;
import java.util.regex.Matcher;
import java.util.regex.Pattern;

@Slf4j
@Service
public class UserService {
    @Resource
    private UserMapper userMapper;
    @Resource
    private AddressMapper addressMapper;

    public ResultVO userRegistration(UserRegistrationVo user) {
        if (StringUtils.isEmpty(user.getUserName())) {
            return new ResultVO(ResultCode.ERROR.getCode(),"用户名不能为空!");
        }
        if (StringUtils.isEmpty(user.getPassWord())) {
            return new ResultVO(ResultCode.ERROR.getCode(),"密码不能为空!");
        }
        boolean isUserNameChineseFlag = isChineseStr(user.getUserName());
        if (isUserNameChineseFlag == true) {
            return new ResultVO(ResultCode.ERROR.getCode(),"用户名不能包含中文!");
        }
        boolean isUserNameSpecialCharFlag = isSpecialChar(user.getUserName());
        if (isUserNameSpecialCharFlag == true) {
            return new ResultVO(ResultCode.ERROR.getCode(),"用户名不能包含特殊字符!");
        }
        boolean isPassWordChineseFlag = isChineseStr(user.getPassWord());
        if (isPassWordChineseFlag == true) {
            return new ResultVO(ResultCode.ERROR.getCode(),"密码不能包含中文!");
        }


        // 判断该用户是否已经注册
        String userRecord = "";
        try {
            userRecord = userMapper.getUserNameRecord(user.getUserName());
        }catch (Exception e) {
            log.error("获取用户注册记录失败:"+e.getMessage());
        }

        if (!StringUtils.isEmpty(userRecord)) {
            return new ResultVO(ResultCode.ERROR.getCode(),"注册失败!该用户名已被注册!");
        }

        SimpleDateFormat sdf = new SimpleDateFormat("yyyy-MM-dd HH:mm:ss");

        // 如果未注册,则插入数据
        ShopUserInfo shopUserInfo = new ShopUserInfo();
        shopUserInfo.setBlance(0.0);
        shopUserInfo.setCreateTime(sdf.format(new Date()));
        shopUserInfo.setUpdateTime(sdf.format(new Date()));
        shopUserInfo.setIsAdmin(0);
        shopUserInfo.setNickName(user.getUserName());
        shopUserInfo.setSex("未知");
        shopUserInfo.setUserName(user.getUserName());
        shopUserInfo.setPassWord(user.getPassWord());

        try {
            userMapper.insertRegistrationInfo(shopUserInfo);
        }catch (Exception e) {
            log.error("插入注册数据失败:"+e.getMessage());
            return new ResultVO(ResultCode.ERROR.getCode(),"注册失败:"+e.getMessage());
        }
        return new ResultVO(ResultCode.SUCCESS.getCode(),"注册成功!请登录!");
    }

    public ResultVO userLogin(String userName,String passWord){
        // 查找是否有该用户
        String userRecord = "";
        try {
            userRecord = userMapper.getUserNameRecord(userName);
        }catch (Exception e){
            log.error("查找注册用户失败:"+e.getMessage());
            return new ResultVO(ResultCode.ERROR.getCode(),"查找用户信息失败:"+e.getMessage());
        }
        if (StringUtils.isEmpty(userRecord)) {
            return new ResultVO(ResultCode.ERROR.getCode(),"查无此用户!");
        }
        // 判断账号或密码是否正确
        String isTrueUser = "";
        try {
            isTrueUser = userMapper.getTrueUserLoginInfo(userName,passWord);
        }catch (Exception e){
            log.error("根据用户名和密码获取用户名失败:"+e.getMessage());
        }

        if (StringUtils.isEmpty(isTrueUser)) {
            return new ResultVO(ResultCode.ERROR.getCode(),"用户名或密码错误!");
        }
        return new ResultVO(ResultCode.SUCCESS.getCode(),"登录成功!");
    }

    public ResultVO userInfo(String userName) {
        ShopUserInfo shopUserInfo = new ShopUserInfo();

        try {
            shopUserInfo = userMapper.getUserInfoByUserName(userName);
        }catch (Exception e) {
            log.error("获取用户信息失败:"+e.getMessage());
            return new ResultVO(ResultCode.ERROR.getCode(),"获取用户信息失败:"+e.getMessage());
        }
        return new ResultVO(ResultCode.SUCCESS,shopUserInfo);
    }

    public ResultVO changeUserInfo(ShopUserInfo user) {
        if (user==null) {
            return new ResultVO(ResultCode.ERROR.getCode(),"传入的用户信息为空,修改失败!");
        }
        if (StringUtils.isEmpty(user.getUserName())) {
            return new ResultVO(ResultCode.ERROR.getCode(),"传入用户名为空,修改失败!");
        }
        // 判断是否有对应用户
        String checkUserName = "";
        try {
            checkUserName = userMapper.findUserNameByUserName(user.getUserName());
        }catch (Exception e) {
            log.error("修改用户信息查找用户名失败:"+user.getUserName()+"=="+e.getMessage());
            return new ResultVO(ResultCode.ERROR.getCode(),"查找用户名失败!");
        }
        if (StringUtils.isEmpty(checkUserName)) {
            return new ResultVO(ResultCode.ERROR.getCode(),"查无此用户名，修改失败!");
        }
        SimpleDateFormat sdf = new SimpleDateFormat("yyyy-MM-dd HH:mm:ss");
        user.setUpdateTime(sdf.format(new Date()));
        try {
            userMapper.updateUserInfoByUserName(user);
        }catch (Exception e) {
            log.error("修改用户信息失败:"+e.getMessage());
            return new ResultVO(ResultCode.ERROR.getCode(),"修改用户信息失败:"+e.getMessage());
        }
        return new ResultVO(ResultCode.SUCCESS.getCode(),"修改成功!");
    }

    public ResultVO changeUserPassWord(String userName,String passWord) {
        if (StringUtils.isEmpty(userName)) {
            return new ResultVO(ResultCode.ERROR.getCode(),"用户名为空，修改失败!");
        }
        if (StringUtils.isEmpty(passWord)) {
            return new ResultVO(ResultCode.ERROR.getCode(),"密码不能为空!");
        }
        // 判断是否有该用户名
        String checkUserName = "";
        try {
            checkUserName = userMapper.findUserNameByUserName(userName);
        }catch (Exception e) {
            log.error("查找是否有该用户名失败:"+userName+"=="+e.getMessage());
            return new ResultVO(ResultCode.ERROR.getCode(),"查找是否有该用户名失败:"+e.getMessage());
        }

        if (StringUtils.isEmpty(checkUserName)) {
            return new ResultVO(ResultCode.ERROR.getCode(),"查无此用户名,修改密码失败!");
        }

        // 判断是否和原密码相同
        String originalPassWord = "";
        try {
            originalPassWord = userMapper.getOrigianlPassWordByUserName(userName);
        }catch (Exception e) {
            log.error("查找原密码失败:"+e.getMessage());
        }

        if (passWord.equals(originalPassWord)) {
            return new ResultVO(ResultCode.ERROR.getCode(),"密码和原密码相同,不需要变更!");
        }
        try {
            userMapper.updateUserPassWord(userName,passWord);
        }catch (Exception e) {
            log.error("修改密码失败:"+passWord+"=="+e.getMessage());
            return new ResultVO(ResultCode.ERROR.getCode(),"修改密码失败:"+e.getMessage());
        }
        return new ResultVO(ResultCode.ERROR.getCode(),"修改密码成功!");
    }

    public ResultVO chargeUserBlance(String userName,Double blance){
        if (StringUtils.isEmpty(userName)) {
            return new ResultVO(ResultCode.ERROR.getCode(),"用户名为空,充值失败!");
        }
        SimpleDateFormat sdf = new SimpleDateFormat("yyyy-MM-dd HH:mm:ss");
        // 获取原本的余额
        Double oriBlance = 0.0;
        try {
            oriBlance = userMapper.getUserBlance(userName);
        }catch (Exception e) {
            log.error("获取充值前余额失败:"+e.getMessage());
            return new ResultVO(ResultCode.ERROR.getCode(),"获取充值前余额失败，禁止充值:"+e.getMessage());
        }
        // 总余额
        Double totalBlance = blance + oriBlance;
        String updateTime = sdf.format(new Date());
        try {
            userMapper.updateUserBlance(userName,totalBlance,updateTime);
        }catch (Exception e) {
            log.error("更新充值余额信息失败:"+e.getMessage());
            return new ResultVO(ResultCode.ERROR.getCode(),"充值失败:"+e.getMessage());
        }

        return new ResultVO(ResultCode.SUCCESS.getCode(),"充值成功!当前余额为:"+totalBlance);
    }

    public ResultVO updateUserAuth(String userName,Integer isAdmin) {
        if (StringUtils.isEmpty(userName)) {
            return new ResultVO(ResultCode.ERROR.getCode(), "用户名为空，调整权限失败!");
        }
        SimpleDateFormat sdf = new SimpleDateFormat("yyyy-MM-dd HH:mm:ss");
        try {
            userMapper.updateUserAuth(userName,isAdmin,sdf.format(new Date()));
        }catch (Exception e) {
            log.error("修改用户权限失败:"+e.getMessage());
            return new ResultVO(ResultCode.ERROR.getCode(),"修改用户权限失败:"+e.getMessage());
        }

        return new ResultVO(ResultCode.SUCCESS.getCode(),"修改用户权限成功!");
    }

    // 根据Unicode编码完美的判断中文汉字和符号
    private static boolean isChinese(char c) {
        Character.UnicodeBlock ub = Character.UnicodeBlock.of(c);
        if (ub == Character.UnicodeBlock.CJK_UNIFIED_IDEOGRAPHS || ub == Character.UnicodeBlock.CJK_COMPATIBILITY_IDEOGRAPHS
                || ub == Character.UnicodeBlock.CJK_UNIFIED_IDEOGRAPHS_EXTENSION_A || ub == Character.UnicodeBlock.CJK_UNIFIED_IDEOGRAPHS_EXTENSION_B
                || ub == Character.UnicodeBlock.CJK_SYMBOLS_AND_PUNCTUATION || ub == Character.UnicodeBlock.HALFWIDTH_AND_FULLWIDTH_FORMS
                || ub == Character.UnicodeBlock.GENERAL_PUNCTUATION) {
            return true;
        }
        return false;
    }

    // 完整的判断中文汉字和符号
    public static boolean isChineseStr(String strName) {
        char[] ch = strName.toCharArray();
        for (int i = 0; i < ch.length; i++) {
            char c = ch[i];
            if (isChinese(c)) {
                return true;
            }
        }
        return false;
    }

    // 判断是否包含特殊字符
    public static boolean isSpecialChar(String str) {
        String regEx = "[ _`~!@#$%^&*()+=|{}':;',\\[\\].<>/?~！@#￥%……&*（）——+|{}【】‘；：”“’。，、？]|\n|\r|\t";
        Pattern p = Pattern.compile(regEx);
        Matcher m = p.matcher(str);
        return m.find();
    }

    public ResultVO deleteUser(String userName){
        if (StringUtils.isEmpty(userName)) {
            return new ResultVO(ResultCode.ERROR.getCode(),"未获取到用户名！");
        }
        // 检查用户名
        String checkUserName = "";
        try {
            checkUserName = userMapper.findUserNameByUserName(userName);
        }catch (Exception e) {
            log.error("删除用户-获取用户失败:"+e.getMessage());
            return new ResultVO(ResultCode.ERROR.getCode(),"查找用户信息失败:"+e.getMessage());
        }
        if (StringUtils.isEmpty(checkUserName)) {
            return new ResultVO(ResultCode.ERROR.getCode(),"查无此用户,删除用户失败!");
        }
        try {
            addressMapper.deleteGoodsAddressByUserName(userName);
        }catch (Exception e) {
            log.error("删除购物地址失败:用户名:"+userName+"=="+e.getMessage());
        }
        try {
            userMapper.deleteUser(userName);
        }catch (Exception e) {
            log.error("删除用户失败:"+e.getMessage());
        }
        return new ResultVO(ResultCode.SUCCESS.getCode(),"删除用户成功:"+userName);
    }

}
